#!/bin/sh

host="localhost"
user=""
password=""

function usage ()
{
	echo "usage: $0 -d database [-u username] [-p] [-h host]"
}
opts=$(getopt -u -l help "d:h:u:p" $@)
set -- ${opts}
while [ true ]; do
	case $1 in
		-d)
		database=$2
		shift;;
		-h) 
		host=$2
		echo $host,"a"
		shift
		;;
		-u)
		user=$2
		shift
		;;
		-p) 
		echo -n "input passwd:"
		stty -echo
		read password
		stty echo;;
		--)
		break;;
		*) usage
		exit 1;;
	esac
	shift
done

echo " "
if [ ! "$database" ]; then
	echo "Missing mandatory -d option (database name)"
	usage
	exit 1
fi
cmd="mysql "${database}" -h "${host}

if [[ -n ${user} ]]; then
	cmd="$cmd -u ${user}"
fi
if [[ -n ${password} ]]; then
	cmd="$cmd --password=${password}"
fi

tables=$(${cmd} -A -e "SHOW TABLES" | sed -e 's/\W//g' | grep -v Tables_in_${database})
query=""
for table in $tables; do 
	query=${query}" SHOW FULL COLUMNS FROM "${table}";SHOW INDEX FROM "${table}";" 
done
data=$($cmd -A -e "${query}" -X | grep -v '<?xml')
xml="<root>"${data}"</root>"
echo $xml | xmllint --format - > ${database}.xml

xsltproc sql2dia_table.xsl ${database}.xml | gzip -c > ${database}.dia

